<?php

require_once 'Pipes/FileSystem/ModelList/Finder.php';
require_once 'Pipes/FileSystem/ModelList/Loader.php';
require_once 'Pipes/Statement/WithTags.php';
require_once 'PipesImpl/Config.php';
require_once 'PipesImpl/Model/Meta.php';

class PipesCore_Models_Finders_ByTags
{
	private $_config;
	private $_loader = null;
	private $_meta = null;
	private $_pdo = null;

	public function __construct(PipesImpl_Config $config, PipesImpl_Model_Meta $meta) {
		$this->_config = $config;
		$this->_loader = new Pipes_FileSystem_ModelList_Loader(
			new Pipes_FileSystem_ModelList_Finder($config)
		);
		$this->_meta = $meta;
	}

	public function find($criteria) {
		assert('is_array($criteria)');

		$query = new Pipes_Statement_WithTags($this->_meta->getName(), $criteria);
		$statement = $this->_config->pdo->prepare($query->value);
		$statement->execute($query->substitutions);

		$result = $statement->fetchAll(PDO::FETCH_ASSOC);
		$statement->closeCursor();
		
		$exploded = explode('_', $this->_meta->getModelName());
		$this->_loader->load(array_pop($exploded));
		$listName = $this->_loader->lastLoaded;

		return new $listName($this->_config, $this->_meta, $result);
	}
}

